package string;

import java.util.*;
import java.util.stream.Collectors;

public class GroupAnagrams {
    public static void main(String[] args) {
        GroupAnagrams anagrams = new GroupAnagrams();
        anagrams.solution(anagrams.strs).stream().forEach(
                val -> {
                    System.out.print(val+" ");
                }
        );
    }
    String[] strs = {"duh","hud","cab","tin","pew","may","ill","buy","bar","max","doc"};
    public List<List<String>> solution(String[] strs) {
        HashMap<String, List<String>> resultMap = new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
            char[] key = strs[i].toCharArray();
            Arrays.sort(key);
            String keyStr = String.valueOf(key);
            if(resultMap.containsKey(keyStr)){
                resultMap.get(keyStr).add(strs[i]);
            } else{
                List<String> list = new ArrayList<>();
                list.add(strs[i]);
                resultMap.put(keyStr, list);
            }
        }

        return new ArrayList<>(resultMap.values());
    }
}
